package com.wlwx.simulator.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.nio.ByteBuffer;

public class Decoder extends LengthFieldBasedFrameDecoder {

    private static int maxFrameLength = 10240;

    public Decoder() {
        super(maxFrameLength, 0, 4, -4, 4);
    }

    @Override
    public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = null;
        try{
            frame = (ByteBuf) super.decode(ctx, in);
            if(frame == null)
                return null;

            ByteBuffer byteBuffer = frame.nioBuffer();
            return CMPPCommand.decode(byteBuffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(frame != null) {
                frame.release();
            }
        }

        return null;
    }
}
